package edu.umn.contactviewer.datastore.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.content.Context;
import android.util.Log;
import edu.umn.contactviewer.Contact;
import edu.umn.contactviewer.datastore.ContactListDataService;
import edu.umn.contactviewer.datastore.CreateContactRequestResponseListener;
import edu.umn.contactviewer.datastore.DeleteContactRequestResponseListener;
import edu.umn.contactviewer.datastore.UpdateContactRequestResponseListener;
import edu.umn.contactviewer.task.DeleteContactsAsyncTask;
import edu.umn.contactviewer.task.GetContactsAsyncTask;
import edu.umn.contactviewer.task.UpdateContactAsyncTask;
import edu.umn.contactviewer.task.PostContactAsyncTask;
import edu.umn.contactviewer.task.PostContactResponseData;
import edu.umn.contactviewer.task.PostContactResponseListener;

public class ContactListDataServiceRESTWebServiceImpl implements
		ContactListDataService {

	private final Context context;

	public ContactListDataServiceRESTWebServiceImpl(Context context) {
		this.context = context;
	}

	public List<Contact> getContactList() {
		ArrayList<Contact> contactList = new ArrayList<Contact>();
		GetContactsAsyncTask task = new GetContactsAsyncTask();
		try {
			contactList = task.execute(new String[] { "" }).get();
		} catch (InterruptedException e) {
			Log.e(getClass().getSimpleName() + " - InterruptedException: ",
					e.toString());
		} catch (ExecutionException e) {
			Log.e(getClass().getSimpleName() + " - ExecutionException: ",
					e.toString());
		}
		return contactList;

	}

	public void storeContact(
			Contact contactToStore,
			final CreateContactRequestResponseListener contactRequestResponseListener) {
		PostContactAsyncTask putContactAsyncTask = new PostContactAsyncTask(
				new PostContactResponseListener() {
					
					public void onResponse(
							PostContactResponseData putContactResponseData) {
						RequestResult createContactRequestResponse = RequestResult.FAIL;
						if (!putContactResponseData.getStatus()
								.equalsIgnoreCase("error")) {
							createContactRequestResponse = RequestResult.SUCCESS;
						}
						contactRequestResponseListener
								.onCreateContactResponse(createContactRequestResponse);
					}
				}, context);

		putContactAsyncTask.execute(new Contact[] { contactToStore });
	}

	public void updateContact(Contact contactToUpdate, UpdateContactRequestResponseListener responseListener) {
		UpdateContactAsyncTask task = new UpdateContactAsyncTask(contactToUpdate, responseListener);
		task.execute(new String[] { "" });
	}

	public void deleteContact(Contact contactToDelete, DeleteContactRequestResponseListener responseListener) {

		DeleteContactsAsyncTask task = new DeleteContactsAsyncTask(contactToDelete, responseListener);
		task.execute(new String[] { "" });
	}
}
